package com.propertyportal.propertylistfragment;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.propertyportal.manageproperty.R;

public class AddProperty extends SherlockFragment{
	private EditText pname;
	private EditText address;
	private EditText price;
	private EditText description;
	private EditText longitude;
	private EditText latitude;
	private Spinner propertyType;
	private Spinner sellingType;
	private Button add;
/*	private TextView statusText;
	private Spinner status;*/
	public final static String ARG_POSITION = "position";
	public static int mCurrentPosition = -1;
	public String returnedString="";
	private SherlockFragmentActivity fa;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
        }
		fa=(SherlockFragmentActivity)super.getActivity();
		// TODO Auto-generated method stub
		View view=inflater.inflate(R.layout.addproperty, container, false);
		pname=(EditText)view.findViewById(R.id.Pname);
		address=(EditText)view.findViewById(R.id.address);
		price=(EditText)view.findViewById(R.id.price);
		description=(EditText)view.findViewById(R.id.description);
		longitude=(EditText)view.findViewById(R.id.longitude);
		latitude=(EditText)view.findViewById(R.id.latitude);
		propertyType=(Spinner)view.findViewById(R.id.propertytype);
		sellingType=(Spinner)view.findViewById(R.id.propertyselling);
		add=(Button)view.findViewById(R.id.addproperty);
		add.setText("Save");
		
		add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				new savedData().execute();
			}
		});
		setHasOptionsMenu(true);
		return view;
	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);
		menu.clear();
		inflater.inflate(R.menu.add, menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()){
		case R.id.back:
			FragmentManager fm = getActivity().getSupportFragmentManager();
            fm.popBackStack();
			return true;
		default:
			
			return super.onOptionsItemSelected(item);
		}

	}
	public void saveData(){
		String urls = "http://192.168.2.38:8080/STTHERESEREALTYWS/webresources/com.propertyportal.entities.property/createProperty/";   
		//id here was upon login of a user;
		int id=20;
		try {
	    	URL url = new URL(urls+id+"/"+URLEncoder.encode(pname.getText().toString().trim(), "ISO-8859-1")+"/"+URLEncoder.encode(description.getText().toString().trim(), "ISO-8859-1")+"/"+URLEncoder.encode(price.getText().toString().trim(), "ISO-8859-1")+"/"+propertyType.getSelectedItemPosition()+"/"+sellingType.getSelectedItemPosition()+"/"+URLEncoder.encode(address.getText().toString().trim(), "ISO-8859-1")+"/"+"124.01413"+"/"+"12.1464316");
	            //  URL url = new URL(urla+from+"/"+to);
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	            conn.setRequestMethod("POST");
	            conn.setRequestProperty("Content-Type", "application/json");
	            if (conn.getResponseCode() != 200) {
	                throw new RuntimeException("Failed : HTTP error code : "
	                        + conn.getResponseCode());
	            } else {
	                System.out.print("Succes");
	            }

	            BufferedReader br = new BufferedReader(new InputStreamReader(
	                    (conn.getInputStream())));

	            String output;
	            System.out.println("Output from Server .... \n");
	            while ((output = br.readLine()) != null) {
	                System.out.println(output);
	                returnedString=output;
	            }

	            conn.disconnect();

	        } catch (MalformedURLException e) {

	            e.printStackTrace();

	        } catch (IOException e) {
	            System.out.println(e.getMessage());
	        }
	}
	private class savedData extends AsyncTask<Void, Void, Void> {

		private ProgressDialog dialog = new ProgressDialog(fa);

		protected void onPreExecute() {

			dialog.setMessage("Saving...");
			dialog.show();
		}

		@Override
		protected Void doInBackground(final Void... unused) {

			try {
				saveData();

			} catch (Exception e) {
				Log.e("", "wala jud ma add", e);
			}
			return null;
		}

		protected void onPostExecute(Void result) {
			if (this.dialog != null) {
				this.dialog.dismiss();
			}
			if(returnedString!=null || returnedString!=""){
			Toast.makeText(getActivity(), returnedString, Toast.LENGTH_LONG).show();
			pname.setText("");
			address.setText("");
			price.setText("");
			description.setText("");
			longitude.setText("");
			latitude.setText("");
			propertyType.setSelection(0);
			sellingType.setSelection(0);
			pname.setFocusable(true);
			}
			else{
			Toast.makeText(getActivity(), "Cannot insert data!", Toast.LENGTH_LONG).show();
			}
            
		}

	}
}
